package com.dlc.shop.distribution.common.listener;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.dto.OrderRefundDto;
import com.dlc.shop.bean.event.OrderRefundSuccessEvent;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.util.Arith;
import com.dlc.shop.distribution.common.constants.DistributionAudit;
import com.dlc.shop.distribution.common.constants.DistributionUserIncomeStateEnum;
import com.dlc.shop.distribution.common.dao.DistributionUserIncomeMapper;
import com.dlc.shop.distribution.common.dao.DistributionUserWalletMapper;
import com.dlc.shop.distribution.common.model.DistributionUserIncome;
import com.dlc.shop.distribution.common.model.DistributionUserWallet;
import com.dlc.shop.distribution.common.model.DistributionUserWalletBill;
import com.dlc.shop.distribution.common.service.DistributionUserIncomeService;
import com.dlc.shop.distribution.common.service.DistributionUserWalletBillService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 退款订单监听
 * @author yami
 */
@Component("orderRefundListener")
@AllArgsConstructor
public class OrderRefundListener {

    private final DistributionUserIncomeMapper distributionUserIncomeMapper;

    private final DistributionUserWalletMapper distributionUserWalletMapper;

    private final DistributionUserWalletBillService distributionUserWalletBillService;

    private final DistributionUserIncomeService distributionUserIncomeService;


    @EventListener(OrderRefundSuccessEvent.class)
    public void distributionOrderRefundSuccessEvent(OrderRefundSuccessEvent event) {
        OrderRefundDto orderRefundDto = event.getOrderRefundDto();

        if (CollectionUtils.isEmpty(orderRefundDto.getOrderItems())) {
            return;
        }
        // 查看是否有分销订单
        List<OrderItem> distributionOrderItemList = orderRefundDto.getOrderItems().stream().filter(orderItem -> StrUtil.isNotEmpty(orderItem.getDistributionCardNo())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(distributionOrderItemList)) {
            return;
        }
        // 处理分销订单
        List<DistributionUserIncome> updateBatchDistributionUserIncomeList = new ArrayList<>();
        List<DistributionUserWalletBill> saveBatchDistributionWalletBillList = new ArrayList<>();
        // 更新订单收入信息
        for (OrderItem orderItem : distributionOrderItemList) {
            // 减少分销员的待结算金额，添加已失效金额
            List<DistributionUserIncome> distributionUserIncomeList = distributionUserIncomeMapper.selectList(new LambdaQueryWrapper<DistributionUserIncome>().eq(DistributionUserIncome::getOrderItemId, orderItem.getOrderItemId()).eq(DistributionUserIncome::getState, 1));
            for (DistributionUserIncome distributionUserIncome : distributionUserIncomeList) {
                DistributionUserWallet distributionUserWallet = distributionUserWalletMapper.selectById(distributionUserIncome.getWalletId());
                if (distributionUserWallet == null) {
                    // 未找到分销员信息
                    throw new YamiShopBindException("yami.distribution.exist.error");
                }

                // 添加分销钱包日志
                distributionUserWallet.setUnsettledAmount(Arith.sub(distributionUserWallet.getUnsettledAmount(), distributionUserIncome.getIncomeAmount()));
                distributionUserWallet.setInvalidAmount(Arith.add(distributionUserWallet.getInvalidAmount(), distributionUserIncome.getIncomeAmount()));
                distributionUserWalletMapper.updateById(distributionUserWallet);

                // 更新收入状态
                updateBatchDistributionUserIncomeList.add(distributionUserIncome);

                // 添加钱包变动日志
                saveBatchDistributionWalletBillList.add(new DistributionUserWalletBill(distributionUserWallet, "分销订单退款失效奖励","Distribution order refund lapse bonus", -distributionUserIncome.getIncomeAmount(), 0.0, distributionUserIncome.getIncomeAmount(), 0.0, 0));
            }
        }

        // 批量更新分销收入状态
        if (CollectionUtils.isNotEmpty(updateBatchDistributionUserIncomeList)) {
            // 修改失效状态，如果
            updateBatchDistributionUserIncomeList.forEach( item -> {
                item.setState(DistributionUserIncomeStateEnum.INVALID.getValue());
                if (item.getReson().equals(DistributionAudit.INCOME_ZERO.getValue())){
                    item.setReson(DistributionAudit.INCOME_TWO.getValue());
                }
            });
            if (distributionUserIncomeService.updateBatchState(updateBatchDistributionUserIncomeList) < 0){
                // 批量更新分销收入状态失败
                throw new YamiShopBindException("yami.distribution.batch.update.income");
            }
//            if (distributionUserIncomeMapper.updateBatchState(updateBatchDistributionUserIncomeList, DistributionUserIncomeStateEnum.INVALID.getValue(), DistributionAudit.INCOME_TWO.getValue()) <= 0) {
//                // 批量更新分销收入状态失败
//                throw new YamiShopBindException("yami.distribution.batch.update.income");
//            }
        }

        // 批量添加钱包变动日志
        if (CollectionUtils.isNotEmpty(saveBatchDistributionWalletBillList)) {
            distributionUserWalletBillService.saveBatch(saveBatchDistributionWalletBillList);
        }
    }
}
